package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtils;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD = "123";

    @Override
    public PageResult<UserDO> list(UserDTO userDto) {
        PageHelper.startPage(userDto.getPage(), userDto.getPageSize());
        List<UserDO> list = userMapper.list(userDto);

        list.forEach(System.out::println);

        Page<UserDO> page = (Page<UserDO>) list;
        return PageResult.<UserDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addUser(User user) {
        /**   不用写,因为BeanUtil会先提前判断是否为空
        if (ObjectUtils.isEmpty(user)){
            throw new RuntimeException("参数错误");
        }*/

        //"id" ,"password", "deptId", "roleId", "image", "remark"这些值都是忽视掉的值,不用检查。  要检查的都是其他的值
        boolean hasnull = BeanUtil.hasNullField(user, "id" ,"password", "roleId","deptId",  "image", "remark","updateTime","createTime");
        if (hasnull) {
            throw new RuntimeException("参数错误");
        }
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        //原始密码
        String password = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD).toString();
        //MD5进行消息摘要
        String up_password = DigestUtils.md5DigestAsHex(password.getBytes());

        user.setPassword(up_password);

        userMapper.addUser(user);
    }

    @Override
    public UserDO getUser(Integer id) {
        return userMapper.getUser(id);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    @Override
    public List<UserDO> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public List<UserDO> getUsersByRole(String roleLabel) {
        return userMapper.getUsersByRole(roleLabel);
    }

    @Override
    public List<UserDO> getUsersByDeptId(Integer deptId) {
        return userMapper.getUsersByDeptId(deptId);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        // 1. 参数合法性校验
        boolean hasNull = BeanUtil.hasNullField(dto);
        if (hasNull){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }

        // 2. 根据用户名查询数据库获取用户对象
        User dbUser = userMapper.selectByUsername(dto.getUsername());

        // 3. 数据合法性校验
        if (Objects.isNull(dbUser)) {
            CommonException.throwException(ParamEnum.LOGIN_USERNAME_ERROR);
        }

        //判断当前用户状态是否为停用
        if (ObjectUtil.equals(dbUser.getStatus(),0)){
            CommonException.throwException(ParamEnum.USER_STATUS_ERROR);
        }

        // 4. 密码校验
        // 4.1获取前端用户传递密码,对其进行MD5
        String encodedPassword = dbUser.getPassword();
        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        boolean equals = ObjectUtil.equals(encodedPassword, userPassword);
        if (!equals){
            CommonException.throwException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }


        // 5. 数据封装返回
        // 5.1 根据角色id查询角色信息 【 角色标签 方式1 多表关联查询  方式2 根据角色id查询角色表】
        Role role = roleMapper.selectByRoleId(dbUser.getRoleId());

        // TODO 生成令牌中需要携带自定义信息
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", dbUser.getId());
        claims.put("username", dbUser.getUsername());

        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(Objects.isNull(role) ? null : role.getLabel())
                .token(JwtUtils.generateToken(claims))
                .build();
    }

    @Override
    public void deleteUser(int id) {
        this.baseMapper.deleteById(id);
    }
}
